package com.meilingcloud.biobank.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.meilingcloud.biobank.domain.SampleBackup;
import com.meilingcloud.biobank.domain.dto.QrCodeExcelDto;
import com.meilingcloud.biobank.domain.dto.SampleCreateSaveDto;
import com.meilingcloud.biobank.domain.dto.SampleImportDto;
import com.meilingcloud.biobank.domain.dto.SampleQueryDto;
import com.meilingcloud.biobank.service.ISampleBackupService;
import com.meilingcloud.common.annotation.Log;
import com.meilingcloud.common.core.controller.BaseController;
import com.meilingcloud.common.core.domain.AjaxResult;
import com.meilingcloud.common.core.page.TableDataInfo;
import com.meilingcloud.common.enums.BusinessType;
import com.meilingcloud.common.utils.SecurityUtils;
import com.meilingcloud.common.utils.poi.ExcelUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 样本复份 Controller
 *
 * @author chenl
 * @date 2021-03-08
 */
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/biobank/sample")
public class SampleBackupController extends BaseController {

    private final ISampleBackupService iSampleBackupService;

    /**
     * 查询样本复份 列表
     */
    @PreAuthorize("@ss.hasPermi('biobank:sample:list')")
    @GetMapping("/list")
    public TableDataInfo list(SampleQueryDto sampleQueryDto) {
        if (CollectionUtil.isNotEmpty(sampleQueryDto.getSamplingRange())) {
            List<Date> dateRange = sampleQueryDto.getSamplingRange().stream().filter(ObjectUtil::isNotNull).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(dateRange)) {
                sampleQueryDto.setSamplingStart(dateRange.get(0));
                sampleQueryDto.setSamplingEnd(dateRange.get(1));
            }
        }
        startPage();
        return getDataTable(iSampleBackupService.queryList(sampleQueryDto));
    }

    /**
     * 查询样本复份列表,包含已删除
     *
     * @param sampleQueryDto sampleQueryDto
     * @return result
     */
    @PreAuthorize("@ss.hasPermi('biobank:sample:list')")
    @GetMapping("/getList")
    public TableDataInfo getListIncludeDeleted(SampleQueryDto sampleQueryDto) {
        if (CollectionUtil.isNotEmpty(sampleQueryDto.getSamplingRange())) {
            List<Date> dateRange = sampleQueryDto.getSamplingRange().stream().filter(ObjectUtil::isNotNull).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(dateRange)) {
                sampleQueryDto.setSamplingStart(dateRange.get(0));
                sampleQueryDto.setSamplingEnd(dateRange.get(1));
            }
        }
        startPage();
        return getDataTable(iSampleBackupService.queryListIncludeDeleted(sampleQueryDto));
    }

    /**
     * 导出样本复份
     */
    @PreAuthorize("@ss.hasPermi('biobank:sample:export')")
    @Log(title = "样本管理 ", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(SampleQueryDto sampleQueryDto) {
        if (CollectionUtil.isNotEmpty(sampleQueryDto.getSamplingRange())) {
            sampleQueryDto.setSamplingStart(sampleQueryDto.getSamplingRange().get(0));
            sampleQueryDto.setSamplingEnd(sampleQueryDto.getSamplingRange().get(1));
        }
        List<SampleBackup> list = iSampleBackupService.queryList(sampleQueryDto);
        ExcelUtil<SampleBackup> util = new ExcelUtil<SampleBackup>(SampleBackup.class);
        return util.exportExcel(list, "样本复份数据");
    }

    /**
     * 导入样本
     */
    @PreAuthorize("@ss.hasPermi('biobank:sample:import')")
    @Log(title = "样本管理 ", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SampleImportDto> util = new ExcelUtil<>(SampleImportDto.class);
        List<SampleImportDto> sampleImportDtos = util.importExcel(file.getInputStream());
        String message = iSampleBackupService.importSample(sampleImportDtos, updateSupport);
        return AjaxResult.success(message);
    }

    /**
     * 导入样本 模板
     */
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate() {
        ExcelUtil<SampleImportDto> util = new ExcelUtil<>(SampleImportDto.class);
        return util.importTemplateExcel("样本导入模板");
    }

    /**
     * 条码/二维码导入模板
     */
    @GetMapping("/importQrCodeTemplate")
    public AjaxResult importQrCodeTemplate() {
        ExcelUtil<QrCodeExcelDto> util = new ExcelUtil<>(QrCodeExcelDto.class);
        return util.importTemplateExcel("条码二维码导入模板");
    }

    /**
     * 获取样本复份 详细信息
     */
    @PreAuthorize("@ss.hasPermi('biobank:sample:query')")
    @GetMapping(value = "/{sampBackupId}")
    public AjaxResult getInfo(@PathVariable("sampBackupId") Long sampBackupId) {
        //自己写sql,因需查询已删除记录
        return AjaxResult.success(iSampleBackupService.getInfoById(sampBackupId));
    }

    /**
     * 新增样本复份
     */
    @PreAuthorize("@ss.hasPermi('biobank:sample:add')")
    @Log(title = "样本管理 ", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SampleBackup sampleBackup) {
        sampleBackup.setCreateBy(SecurityUtils.getUsername());
        return toAjax(iSampleBackupService.save(sampleBackup));
    }

    /**
     * 修改样本复份
     */
    @PreAuthorize("@ss.hasPermi('biobank:sample:edit')")
    @Log(title = "样本管理 ", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SampleBackup sampleBackup) {
        sampleBackup.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(iSampleBackupService.updateById(sampleBackup));
    }

    /**
     * 修改样本复份，可修改已删除记录
     *
     * @param sampleBackup sampleBackup
     * @return boolean
     */
    @PreAuthorize("@ss.hasPermi('biobank:sample:edit')")
    @Log(title = "样本管理 ", businessType = BusinessType.UPDATE)
    @PutMapping("/update")
    public AjaxResult updateById(@RequestBody SampleBackup sampleBackup) {
        sampleBackup.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(iSampleBackupService.updateSampleBackup(sampleBackup));
    }

    /**
     * 删除样本复份
     * 删除样本复份时需要同时清除冻存管表的样本复份，为了解决交叉引用，将删除接口写在tubeController中
     * 此接口只在删除虚拟状态样本复份使用
     */
    @PreAuthorize("@ss.hasPermi('biobank:sample:remove')")
    @Log(title = "样本管理 ", businessType = BusinessType.DELETE)
    @DeleteMapping("/{sampBackupIds}")
    public AjaxResult remove(@PathVariable Long[] sampBackupIds) {
        return toAjax(iSampleBackupService.removeByIds(Arrays.asList(sampBackupIds)));
    }

    /**
     * 创建新样本
     */
    @PreAuthorize("@ss.hasPermi('biobank:sample:add')")
    @Log(title = "样本管理 ", businessType = BusinessType.INSERT)
    @PostMapping("/create")
    public AjaxResult createSample(@Valid @RequestBody SampleCreateSaveDto sampleCreateSaveDto) {
        return toAjax(iSampleBackupService.saveSample(sampleCreateSaveDto));
    }

    /**
     * 批量更新
     */
    @PreAuthorize("@ss.hasPermi('biobank:sample:edit')")
    @Log(title = "样本管理 ", businessType = BusinessType.UPDATE)
    @PostMapping("/updateSamples")
    public synchronized AjaxResult updateSamples(@RequestBody List<SampleBackup> sampleBackups) {
        List<SampleBackup> collect = sampleBackups.stream().map(item -> {
            item.setUpdateBy(SecurityUtils.getUsername());
            return item;
        }).collect(Collectors.toList());
        return toAjax(iSampleBackupService.updateBatchById(collect));
    }

    /**
     * 根据qrCode查询样本信息
     */
    @PostMapping("/getSampleByQrCode")
    public AjaxResult getSampleByQrCode(@RequestBody SampleBackup sampleBackup) {
        return AjaxResult.success(iSampleBackupService.queryByQrCode(sampleBackup));
    }

    /**
     * 获取同样本其他复份信息
     */
    @PostMapping("/getSameSamples")
    public AjaxResult getSameSamples(@RequestBody SampleBackup sampleBackup) {
        return AjaxResult.success(iSampleBackupService.querySameSamples(sampleBackup));
    }

    /**
     * 获取样本复份生命周期
     */
    @GetMapping("/getSampleLifeCycle/{sampBackupId}")
    public AjaxResult getSampleLifeCycle(@PathVariable("sampBackupId") Long sampBackupId) {
        return AjaxResult.success(iSampleBackupService.getSampleLifeCycle(sampBackupId));
    }

}
